import router from "@/router";
import {useLoginUserStore} from "@/stores/user.ts";
import {message} from "ant-design-vue";

let firstFetchLoginUser = true;


router.beforeEach(async (to, from, next) => {
    const loginUserStore = useLoginUserStore();
    let loginUser = loginUserStore.getLoginUser;
    if (firstFetchLoginUser) {
        await loginUserStore.fetchLoginUser();
        loginUser = loginUserStore.getLoginUser;
        firstFetchLoginUser = false;
    }
    const toURL = to.fullPath;
    if (toURL.startsWith("/admin")) {
        if (!loginUser || loginUser().userRole !== 'admin') {
            message.error("无权限访问");
            next(`/user/login?redirect=${toURL}`);
            return
        }
    }
    next();
});
